package yannan.voiplock4ble.task;

import android.util.Log;

import com.google.gson.Gson;

import org.greenrobot.greendao.annotation.NotNull;

import java.util.List;

import yannan.voiplock4ble.base.MyApplication;
import yannan.voiplock4ble.bean.CommonResponse;
import yannan.voiplock4ble.bean.LockKeyBean;
import yannan.voiplock4ble.bean.LockKeyBeanDao;
import yannan.voiplock4ble.bean.VeinKeyBean;
import yannan.voiplock4ble.bean.VeinKeyBeanDao;
import yannan.voiplock4ble.db.DaoUtils;
import yannan.voiplock4ble.db.MyDBHelper;
import yannan.voiplock4ble.db.daomanager.LockKeyDaoManager;
import yannan.voiplock4ble.db.daomanager.VeinKeyDaoManager;
import yannan.voiplock4ble.net.NetUtils;
import yannan.voiplock4ble.net.base.NetworkCallBack;
import yannan.voiplock4ble.utils.TimeUtils;

/**
 * 说明：上传指静脉/密码钥匙子线程
 * 作者：mainTel
 * 时间：2016/11/23 10:14
 * 备注：
 */
public class UpLoadLockKeyTask extends Thread {

    String lockserialId;
    String keyType; // 上传类型 0 指静脉 1密码

    public static UpLoadLockKeyTask create(@NotNull String lockserialId, @NotNull String keyType) {
        UpLoadLockKeyTask recordTask = new UpLoadLockKeyTask();
        recordTask.lockserialId = lockserialId;
        recordTask.keyType = keyType;
        return recordTask;
    }


    @Override
    public void run() {
        uploadKey();
    }

    /**
     * 查询用户并上传
     */
    private void uploadKey() {
        List<LockKeyBean> list = DaoUtils.getDao(LockKeyDaoManager.class).getQueryBuilder()
                .where(LockKeyBeanDao.Properties.LockserialId.eq(lockserialId), LockKeyBeanDao.Properties.Type.eq(keyType))
                .list();
        Gson gson = new Gson();
        StringBuffer sb = new StringBuffer();
        sb.append("[");
        int i = 0;
        for (LockKeyBean bean :
                list) {
            sb.append(gson.toJson(bean));
            i++;
            if (i < list.size()) {
                sb.append(",");
            }
        }
        sb.append("]");
        if (MyApplication.getInterface().userBean != null)
            NetUtils.getNetworkService().uploadLockUserInfo(sb.toString()
                    , MyApplication.getInterface().userBean.userId)
                    .enqueue(new NetworkCallBack<CommonResponse>() {
                        @Override
                        public void onSuc(CommonResponse resBody) {
                            Log.d("way","指静脉上传成功"+resBody.returnValue);
                            //修改本地的时间
                            if (resBody != null)
                                MyDBHelper.upDateLocalTime(lockserialId, resBody.returnValue, keyType);
                        }

                        @Override
                        public void onFail(String msg) {
                            Log.d("way","指静脉上传失败");
                            // TODO: 2016/11/24 是否进行重复上传
                        }
                    });
    }
}
